package com.starry.push.netty.controller;

import com.starry.push.netty.domain.LogAccessToken;
import com.starry.push.netty.service.LogAccessTokenService;
import com.starry.push.netty.service.SystemPersonnelService;
import com.starry.push.netty.vo.GetTokenCondition;
import com.starry.push.netty.vo.ResponseResult;
import com.starry.push.netty.vo.Token;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author WuChao
 * @version 1.0
 * @date 2020/11/3 14:24
 */
@RestController
@RequestMapping("/access")
@Slf4j
@AllArgsConstructor
public class AccessController {

    private SystemPersonnelService systemPersonnelService;
    private LogAccessTokenService logAccessTokenService;
    private RedisTemplate redisTemplate;

    @PostMapping("/token")
    public ResponseEntity getAccessToken(@Validated GetTokenCondition condition) {
        log.info("获取token：{}", condition);
        Boolean checkAuthentication = systemPersonnelService.checkAuthentication(condition.getClientType(), condition.getAccessKey(), condition.getAccessSecret());
        if (!checkAuthentication) {
            return ResponseEntity.ok(ResponseResult.error("认证信息有误"));
        }
        String token = UUID.randomUUID().toString();
        LogAccessToken logAccessToken = new LogAccessToken();
        logAccessToken.setAccessKey(condition.getAccessKey());
        logAccessToken.setClientType(condition.getClientType());
        logAccessToken.setCreateTime(LocalDateTime.now());
        logAccessToken.setAccessToken(token);
        LocalDateTime minutes = LocalDateTime.now().plusMinutes(10);
        logAccessToken.setExpireTime(minutes);
        boolean isSave = logAccessTokenService.save(logAccessToken);
        redisTemplate.boundValueOps(token).set(condition, 10, TimeUnit.MINUTES);
        Token getToken = Token.builder()
                .token(token)
                .expireTime(minutes)
                .build();
        return ResponseEntity.ok(getToken);
    }











}
